package javaserialize;

import theobj.BlackCat;

import java.io.*;

public class SuperMain {
    private static final String FILE_PATH = "./super.bin";
 
    public static void main(String[] args) throws Exception {

        showMeSizeAndTime();
/*
        // 序列化的大小
        showMeSize();

        // 序列化的时间 1000次
        showMeTime();
*/
    }

    private static void showMeSizeAndTime() throws Exception {

        // 序列化的大小
        showMeSize();

        // 序列化的时间 1000次
        showMeTime();

    }


    //序列化为byte[]
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            byte[] b = bos.toByteArray();
            return b;
        } catch (IOException e) {
            System.out.println("序列化失败 Exception:" + e.toString());
            return null;
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException ex) {
                System.out.println("io could not close:" + ex.toString());
            }
        }
    }


    private static void showMeTime() throws Exception {
        long start = System.currentTimeMillis();
        BlackCat black = new BlackCat("black", "我是黑猫");
        for (int i = 0; i < 100000; i++) {
//            serialize(black);
            serialize(new BlackCat("black", "我是黑猫"));
        }
        System.out.println("java serializable 耗时: " + (System.currentTimeMillis() - start));
    }

    private static void showMeSize() throws Exception {
        BlackCat black = new BlackCat("black", "我是黑猫");
        System.out.println("java serializable 大小：" + serialize(black).length);
    }

    private static void serializeAnimal() throws Exception {
        BlackCat black = new BlackCat("black", "我是黑猫");
        System.out.println("序列化前："+black.toString());
        System.out.println("=================开始序列化================");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
        oos.writeObject(black);
        oos.flush();
        oos.close();
    }
 
    private static void deserializeAnimal() throws Exception {
        System.out.println("=================开始反序列化================");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH));
        BlackCat black = (BlackCat) ois.readObject();
        ois.close();
        System.out.println(black);
    }
}